//
//  IMIRotateView.swift
//  IMIHome
//
//  Created by Roffa Zhou on 2021/8/12.
//  Copyright © 2021 上海创米科技有限公司. All rights reserved.
//

import UIKit

open class IMIRotateView: UIView {
    public var flagColor: UIColor = .black
    public var text: NSString?
    
    public func update(){  //更新视图， 有对属性赋值后，最后应该调用此方法
        setNeedsDisplay()
    }
    
   
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    open override func draw(_ rect: CGRect) {
        guard Int(rect.width) == Int(rect.height) else {
            fatalError("IMIRotateView必须定义为方形")
        }
        // Drawing code
        let context = UIGraphicsGetCurrentContext()
        UIColor.clear.set()  //背景色
        
        /**绘制背景图*/
        let points = [CGPoint.zero, CGPoint(x: rect.width*0.5, y: 0), CGPoint(x: rect.width, y: rect.height * 0.5), CGPoint(x: rect.width, y: rect.height),  CGPoint.zero]
        context?.addLines(between: points)
        context?.setFillColor(flagColor.cgColor)
        context?.drawPath(using: CGPathDrawingMode.fillStroke)
        context?.saveGState()  //保存状态
        context?.translateBy(x: rect.width * 0.35, y: -rect.height * 0.05)
        context?.rotate(by: .pi / 4.0)
        
        /**绘制文字*/
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = .center
        text?.draw(in: CGRect(x: 0, y: 0, width: rect.width, height: rect.size.height*0.5), withAttributes: [.font: UIFont.boldSystemFont(ofSize: 10),
            .foregroundColor: UIColor.white,
            .paragraphStyle : paragraph
        ])
        context?.restoreGState()
    }
    

}
